import React, { useState, useEffect } from 'react';
import { Button, Result, Statistic } from 'antd';
import { useLocation, useNavigate } from 'react-router-dom';

const { Countdown } = Statistic;

const ApiStatusPage: React.FC = () => {
    const location = useLocation();
    const navigate = useNavigate();
    const [countdown, setCountdown] = useState(10); // 10秒倒计时
    const [isCounting, setIsCounting] = useState(true);

    // 从location.state获取参数，如果没有则使用默认值
    const {
        title = "Successfully Purchased Cloud Server ECS!",
        message = "Cloud server configuration takes 1-5 minutes, please wait.",
        callbackUrl = "/user/login",
        status = "success"
    } = location.state || {} as any;

    useEffect(() => {
        let timer: NodeJS.Timeout;
        
        if (isCounting && countdown > 0) {
            timer = setTimeout(() => {
                setCountdown(countdown - 1);
            }, 1000);
        } else if (isCounting && countdown === 0) {
            // 倒计时结束，自动跳转
            navigate(callbackUrl);
        }

        return () => {
            if (timer) clearTimeout(timer);
        };
    }, [countdown, isCounting, navigate, callbackUrl]);

    const handleConfirm = () => {
        // 手动确认，停止倒计时并跳转
        setIsCounting(false);
        navigate(callbackUrl);
    };

    const handleCountdownClick = () => {
        // 点击倒计时可以暂停/继续
        setIsCounting(!isCounting);
    };

    return (
        <Result
            status={status}
            title={title}
            icon={<></>}
            subTitle={
                <div>
                    <p>{message}</p>
                    <p>将在 <span 
                        style={{color: '#1890ff', cursor: 'pointer', fontWeight: 'bold'}}
                        onClick={handleCountdownClick}
                    >
                        {countdown}
                    </span> 秒后自动跳转...</p>
                    {!isCounting && <p style={{color: '#ff4d4f'}}>倒计时已暂停，点击确认按钮手动跳转</p>}
                </div>
            }
            extra={[
                <Button type='primary' key="buy" onClick={handleConfirm}>
                    确认 ({countdown}s)
                </Button>,
            ]}
        />
    );
};

export default ApiStatusPage;